﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace BusinessComponents.Common
{
    public static class BaseSorting
    {
        public static DataTable LinqToDataTable(this  IEnumerable<RoomType> enumberable)
        {
            DataTable dt = new DataTable();

            RoomType first = enumberable.FirstOrDefault();
            if (first == null)  // return if the resultset is empty
                return dt;

            Type t = first.GetType();
            PropertyInfo[] properties = t.GetProperties();

            // Adding columns to the datatable from the property info
            foreach (PropertyInfo pi in properties)
            {
                Type pt = pi.PropertyType;

                // Handling nullable properties in the resultset
                if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
                    pt = Nullable.GetUnderlyingType(pt);

                dt.Columns.Add(pi.Name, pt);
            }

            // Adding rows to the datatable from the enumerable resultset
            foreach (object obj in enumberable)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in properties)
                {
                    object value = (pi.GetValue(obj, null) != null) ? pi.GetValue(obj, null) : DBNull.Value;
                    dr[pi.Name] = value;
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }
    }
}
